<?php
namespace Helpers;

use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysUserextrapower;
use Admin\Models\user\XhsysUser;
use Modules\Power;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Di;
use Services\UserService;

class User
{
    private static $enum = [
        'bDisable'  => [0 => '否', 1 => '是'],
        'bHistory'  => [0 => '否', 1 => '是'],
        'bCompany'  => [0 => '否', 1 => '是'],
        'iUserSex'  => [0 => '未知', 1 => '男', 2 => '女']
    ];

    /**
     * 获取枚举
     *
     * @param $field
     * @return array
     *
     * create by ck 20181112
     */
    public static function getEnum($field = null)
    {
        self::$enum['iUserType'] = Enum::getEnum('用户类型');
        self::$enum['iSubject'] = Enum::getEnum('学科');
        return $field ? self::$enum[$field] : self::$enum;
    }

    /**
     * 判断是否登陆
     *
     * @return bool
     *
     * create by ck 20180222
     */
    public static function isLogin()
    {
        return array_key_exists('auth', $_SESSION);
//        return !!$_SESSION['auth'];
    }

    /**
     * 是否为超级管理员
     *
     * @return bool
     *
     * create by ck 20171228
     * modify by ck 20180903
     */
    public static function isAdmin()
    {
        $adminUser = ['admin'];
        return in_array(strtolower(Main::getLoginUserInfo('logonName')), $adminUser);
    }

    /**
     * 获取当前用户id
     *
     * @return bool
     *
     * create by ck 20180329
     */
    public static function getId()
    {
        return intval(Main::getLoginUserInfo('userId'));
    }

    /**
     * 根据用户id获取登录名
     *
     * @param $userId
     * @return mixed|string
     * @throws \Exception
     *
     * create by ck 20180427
     */
    public static function getLogonName($userId)
    {
        static $arr = [];
        if (array_key_exists($userId, $arr)) {
            return $arr[$userId];
        }
        $user = XhsysUser::findFirst([
            'columns'    => 'sLogonName',
            'conditions' => 'iUserId = :userId:',
            'bind'       => ['userId' => $userId]
        ]);
        if (!$user) {
            throw new \Exception('无该用户信息');
        }
        $arr[$userId] = $user->sLogonName;
        return $user->sLogonName;
    }

    /**
     * 根据关键字匹配返回姓名id
     *
     * @param $key
     * @param $withName
     * @return array
     *
     * create by qgz 20180621
     */
    public static function searchUser($key, $withName = false)
    {
        $users = XhsysUser::find([
            'columns' => 'iUserId, sUserName',
            'conditions' => "bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND sUserName LIKE '%{$key}%'"
        ])->toArray();
        $machIds = array_column($users, 'sUserName', 'iUserId');
        return $withName ? $machIds : array_keys($machIds);
    }

    /**
     * 检查用户是否为员工
     *
     * @param null $userId
     * @return array|bool|string
     * @throws \Exception
     *
     * create by ck 20180408
     * modify by ck 20190222    读取数据库判断（兼容新方式）
     */
    public static function isStaff($userId = null)
    {
        $userId or $userId = self::getId();
        if (!$userId) {
            throw new \Exception('无用户id');
        }
//        if ($userId == self::getId()) {
//            return Main::getLoginUserInfo('isStaff');
//        }
        return !!XhhrmStaff::count("bDelete = 0 AND iUserId = {$userId}");
    }

    /**
     * 用户登陆
     *
     * @param string $account
     * @param string $password
     * @param string $smsCode
     * @param bool $isTrust         --是否信任
     * @return bool
     * @throws \Exception
     *
     * create by ck 20171221
     * modify by ck 20180408    超级管理员添加短信验证码验证
     * modify by ck 20180411    学生禁止登陆
     * modify by ck 20180412    发送登陆短信
     * modify by ck 20180428    逻辑更改
     * modify by ck 20180515    添加短信验证标记
     * modify by ck 20180522    家长禁止登陆（员工除外）
     * modify by ck 20180628    信任，短信登陆无需密码
     */
    public static function login(string $account, string $password, string $smsCode = '', bool $isTrust = false)
    {
        $sysConfig      = Main::getConfigByName('admin');
        $needSmsCodeDep = Tool::getValue($sysConfig, 'needSmsCodeDep', [], function ($value) {
            return array_filter(explode('|', $value));
        });
        $depInfo = [];
        $verifyPhone = false;

        $user = Di::getDefault()->get('modelsManager')->createBuilder()
            ->columns(['u.iUserId', 'u.sLogonName', 'u.sUserName', 'u.iUserType', 'u.sLogonPwd', 'u.sSelfPhone', 'u.iSchoolId'])
            ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
            ->leftJoin('\\Admin\\Models\\hrm\\XhhrmStaff', 'u.iUserId = s.iUserId AND s.bDelete = 0', 's')
            ->where('u.bDelete = 0 AND u.bDisable = 0')
            ->andWhere('u.sLogonName = :account: OR u.sSelfPhone = :account:', ['account' => $account])
            ->orderBy('s.iStaffId DESC,u.iUserId ASC')
            ->limit(1)
            ->getQuery()->execute()->toArray();
        if (!$user) {
            throw new \Exception('用户不存在');
        }
        $user = (object)$user[0];

        //获取用户部门
        try {
            $depInfo = Hrm::getDepInfoByUser($user->iUserId);
        } catch (\Exception $e) {
        }

        //判断验证码登陆
        if (!$isTrust) {
            if ($account == 'admin') {
                $phone = Tool::getValue($sysConfig, 'phone');
                if ($phone) {
                    if (!$smsCode) {
                        throw new \Exception('超级管理员需短信验证', 401);
                    }
                    if (!Main::checkValidCode($phone, $smsCode)) {
                        throw new \Exception('短信验证码不正确');
                    }
                    $verifyPhone = true;
                }
            } else {
                $checkDep = array_intersect($needSmsCodeDep, array_column($depInfo, 'tag'))
                    || $needSmsCodeDep[0] == 'all';
                if ($checkDep && $user->sSelfPhone) {
                    if (!$smsCode) {
                        throw new \Exception('需要短信验证', 401);
                    } elseif (!Main::checkValidCode($user->sSelfPhone, $smsCode)) {
                        throw new \Exception('短信验证码不正确');
                    }
                    $verifyPhone = true;
                }
            }
        }

        if (!$verifyPhone && strtolower($user->sLogonPwd) != md5($password)) {
            throw new \Exception('密码错误');
        }
        $isStaff = User::isStaff($user->iUserId);
        if (!$isStaff && in_array($user->iUserType, [1, 5])) {
            throw new \Exception('禁止登陆');
        }

        $_SESSION['auth'] = [
            'userId'        => $user->iUserId,
            'logonName'     => $user->sLogonName,
            'userName'      => $user->sUserName,
            'userType'      => $user->iUserType,
            'schoolId'      => $user->iSchoolId,
            'isStaff'       => $isStaff,    //可移除
            'depId'         => array_column($depInfo, 'id'),
            'depTag'        => array_filter(array_column($depInfo, 'tag')),
            'depName'       => array_column($depInfo, 'name'),
            'verifyPhone'   => $verifyPhone //可移除
        ];
        if (Tool::getValue($sysConfig, 'loginNotice') == 'true' && $user->sSelfPhone) {
            try {
                Main::sendSMS(
                    $user->sSelfPhone,
                    '您的账号' . $account . '于' . date('Y-m-d H:i:s') . '成功登陆管理后台，若非本人操作，请及时联系管理员。',
                    'admin',
                    'login'
                );
            } catch (\Exception $e) {
            }
        }
        Di::getDefault()->get('cookies')->set('userInfo', json_encode([
            'LogonName' => $user->sLogonName,
            'UserName'  => $user->sUserName,
            'UserId'    => $user->iUserId,
            'UserType'  => $user->iUserType
        ]));
    }

    /**
     * 检查是否有所有学校权限
     *
     * @param null $userId
     * @return bool
     *
     * create by ck 20171229
     */
//    public static function allSchoolPower($userId = null)
//    {
//        if (!$userId && self::isAdmin()) {
//            return true;
//        }
//        $powerIds = UserPower::getExtraSchoolPower($userId ?: Main::getLoginUserInfo('userId'));
//        if (!$powerIds) {
//            return false;
//        }
//        if ((isset($powerIds['manage']['all']) && $powerIds['manage']['all'] == 'true')
//            || (isset($powerIds['view']['all']) && $powerIds['view']['all'] == 'true')
//        ){
//            return true;
//        }
//        return false;
//    }

    /**
     * 获取有权限学校列表
     *
     * @param bool $withName    --是否返回学校名称
     * @param null $targetId    --目标用户id
     * @param bool $merge       --是否合并权限（交集）
     * @return array|bool
     *
     * create by ck 20171228
     * modify by ck 20180205    方法抽离，扩展
     */
    public static function getSchool($withName = false, $targetId = null, $merge = false)
    {
        $power = $merge ? School::getMergePower($targetId, $withName) : School::getPower($withName, $targetId);
        return $power === true ? School::getSchools() : $power;
//        if (!$targetId && self::isAdmin()) {
//            return XhschoolInfo::getSchoolSupportArray($withName);
//        }
//        $schoolIds = self::getSchoolPower(false, $targetId, false);
//        if (!$schoolIds) {
//            return [];
//        }
//        if ($merge && $targetId != Main::getLoginUserInfo('userId') && !self::isAdmin()) {
//            $mergeSchoolIds = self::getSchoolPower();
//            $schoolIds = array_intersect($schoolIds, $mergeSchoolIds);
//        }
//        if ($withName) {
//            $schoolArr = XhschoolInfo::getSchoolSupportArray();
//            $tempArr   = [];
//            foreach ($schoolIds as $schId) {
//                $tempArr[$schId] = $schoolArr[$schId];
//            }
//            $schoolIds = $tempArr;
//        }
//        return $schoolIds ?: [];
    }

    /**
     * 获取学校权限
     *
     * @param bool $withName
     * @param null $userId
     * @param bool $boolSuccess
     * @return array|bool
     *
     * create by ck 20180205
     * modify by ck 20180615
     */
    public static function getSchoolPower($withName = false, $userId = null, $boolSuccess = false)
    {
        if ($boolSuccess) {
            return School::getPower($withName, $userId);
        }
        else {
            $powerIds = School::getPower(false, $userId);
            $schools  = School::getSchools();
            if ($powerIds === true) {
                return $withName ? $schools : array_keys($schools);
            }
            $schoolIds = [];
            foreach ($powerIds as $id) {
                $schoolIds[$id] = $schools[$id];
            }
            return $withName ? $schoolIds : array_keys($schoolIds);
        }
//        if (!$userId && self::isAdmin()) {
//            return $boolSuccess ? true : XhschoolInfo::getSchoolSupportArray($withName);
//        }
//        $powers = UserPower::getExtraSchoolPower($userId ?: Main::getLoginUserInfo('userId'));
//        if (!$powers) {
//            return [];
//        }
//        if ((isset($powers['manage']['all']) && $powers['manage']['all'] == 'true')
//            || (isset($powers['view']['all']) && $powers['view']['all'] == 'true')
//        ){
//            return $boolSuccess ? true : XhschoolInfo::getSchoolSupportArray($withName);
//        }
//        else {
//            $schoolIds = array_values(array_filter(array_unique(array_merge(
//                $powers['manage']['id'] ?: [],
//                $powers['view']['id'] ?: []
//            ))));
//            if ($withName) {
//                $schoolArr = XhschoolInfo::getSchoolSupportArray();
//                $tempArr   = [];
//                foreach ($schoolIds as $schId) {
//                    $tempArr[$schId] = $schoolArr[$schId];
//                }
//                $schoolIds = $tempArr;
//            }
//            return $schoolIds ?: [];
//        }
    }

    /**
     * 修改用户密码
     *
     * @param $userIds
     * @param $password
     * @param $alreadyMd5
     * @param $resetComplete
     * @throws \Exception
     *
     * create by ck 20180205
     * modify by ck 20180825    接入用户服务
     */
    public static function setPassword($userIds, $password, $alreadyMd5 = false, $resetComplete = false)
    {
        UserService::resetPassword($userIds, $password, $alreadyMd5, $resetComplete);
//        if (!$userIds) {
//            throw new \Exception('用户id不能为空');
//        }
//        if (is_string($userIds) || is_int($userIds)){
//            $userIds = [$userIds];
//        }
//        if (!$password) {
//            throw new \Exception('密码不能为空');
//        }
////        $userIdStr = implode(',', $userIds);
//        $md5Pwd    = $alreadyMd5 ? strtoupper($password) : strtoupper(md5($password));
////        $oldDBName = Main::getConfigByName('oldCenterDB')['dbname'];
//        try {
//            //admin不同步
////            if (!array_search('26727', $userIds)) {
////                $oldDB = new Mysql(Main::getConfigByName('oldCenterDB'));
////                $result = $oldDB->execute("UPDATE users SET us_passwd = :password WHERE us_id IN (" . $userIdStr . ")", ['password' => $password]);
////                if (!$result) {
////                    throw new \Exception('老后台更新失败');
////                }
////            }
//            $updateStr = 'UPDATE Admin\\Models\\user\\XhsysUser SET sLogonPwd = :password: WHERE iUserId IN ({userId:array})';
//            $result = Di::getDefault()->get('modelsManager')->executeQuery($updateStr, ['password' => $md5Pwd, 'userId' => $userIds]);
//            if (!$result) {
//                throw new \Exception('修改失败');
//            }
////            $httpClient = new HttpClient(Main::getConfigByName('cLogin')['url']);
////            $response = $httpClient->post('/refreshUserInfo',
////                ['K' => json_encode(['type' => 'batch', 'oUserId' => $userIdStr])]);
////            $body = $response->toArray();
////            if (!isset($body['R']) || $body['R'] != 200){
////                throw new \Exception('刷新失败;' . ($body['I'] ?: $body));
////            }
//        }
//        catch (\Exception $e){
//            throw new \Exception($e->getMessage());
//        }
    }

    /**
     * 获取部门扩展权限id
     *
     * @param $type
     * @param $target
     * @param null $userId
     * @param bool $boolSuccess
     * @return array|bool|string
     *
     * create by ck 20180329
     */
    public static function getExtraPower($type, $target, $userId = null, $boolSuccess = false)
    {
        $powerIds = Power::getExtraPower($type, $target, $userId);
        if (!$boolSuccess && $powerIds === true) {
            return array_column(Hrm::getDepArray(null, 1), 'id');
        }
        return $powerIds;
//        if (!$userId && self::isAdmin()) {
//            goto returnAll;
//        }
//        !$userId and $userId = self::getId();
//        $power = XhsysUserextrapower::findFirst([
//            'conditions' => 'bDelete = 0 AND iGoal = 1 AND iGoalId = :userId: AND sType = :type: AND sTarget = :target:',
//            'bind'       => ['userId' => $userId, 'type' => $type, 'target' => $target]
//        ]);
//        if (!$power) {
//            return [];
//        }
//        if ($power->bAll) {
//            goto returnAll;
//        }
//        return $power->mContent;
//
//        returnAll:
//            return $boolSuccess ? true : array_column(Hrm::getDepArray(null, 1), 'id');
    }

    public static function getPhoneNum($userId)
    {
        $userIds = is_array($userId) ? $userId : [$userId];

        if (is_array($userId)) {

        }
        return [];
    }

}